<template>
	<div class="dynamic-table">
		动态表格
		<comp-dynamic-form  ref="tableInstance" :data="formData" :rules="reportRules" :can-edit="true" />
		<!-- <comp-dynamic-table  ref="tableInstance" :data="formData" :start-row="startRow" :rules="reportRules" :can-edit="true" /> -->
	</div>
</template>
<script lang="ts" setup>
import { formTableColumns,listTableColumns } from "./table";
import { isEmpty, isEmptyObj } from "@/utils/index";
import CompDynamicForm from "@/components/CompDynamicTableReport/form.vue";
import CompDynamicTable from "@/components/CompDynamicTableReport/table.vue";
interface Props {
	action?: string;
}

const props = withDefaults(defineProps<Props>(), {
	action: "edit"
});

const { proxy } = getCurrentInstance()!;

const reportType = "form";
const startRow = 2;
const reportRules = ref<any>([]);
const formData = ref<any>({});
onMounted(() => {
	initData();
});

function initData() {
	// const ret = packageData([], formTableColumns);
	const ret = packageData([], formTableColumns);
	reportRules.value = coverArrayToTable(ret);
	formData.value = {};
	console.log('reportData',reportRules.value);	
}

function packageData(results, items) {
	let resultsLen = 0;
	let saveRow = -1;
	let newItems: any = [];
	let sumCol = 0;
	let LOCK = true;
	let ISHJ = false;

	if (results) {
		resultsLen = results.length;
	}
	if (reportType === "form") {
		// 计算一行中的列头和列尾
		items.forEach((item, index) => {
			item.endRow = false;
			item.startRow = false;
			if (index === 0) {
				item.startRow = true;
			} else if (item.cellRow > saveRow) {
				item.startRow = true;
				newItems[index - 1].endRow = true;
			}
			if (item.cellTableField && resultsLen == 1) {
				item.cellTableFieldValue = results[0][item.cellTableField];
			}
			saveRow = item.cellRow;
			newItems.push(item);
		});
	} else {
		items.forEach((item, index) => {
			item.endRow = false;
			item.startRow = false;
			if (index === 0) {
				item.startRow = true;
			} else if (item.cellRow > saveRow && item.cellRow <= startRow) {
				//找出第一行最后一格
				if (props.action === "edit") {
					if (item.cellRow == 1) {
						const tempItem = { ...item }; //增加操作头部
						tempItem.inputTip = "";
						tempItem.cellType = "show";
						tempItem.fieldShowText = "操作";
						tempItem.mergedColCount = 1;
						tempItem.endRow = true;
						tempItem.cellRow = 0;
						tempItem.mergedRowCount = startRow;
						newItems.push(tempItem);
					} else {
						newItems[index].endRow = true;
					}
				} else {
					newItems[index - 1].endRow = true;
				}
				item.startRow = true;
			}

			if (item.cellRow < startRow) {
				if (item.cellRow == startRow - 1) {
					sumCol = sumCol + 1; //获取流表列数，为了增加删除一列数据
				}
				newItems.push(item);
			} else if (item.cellRow == startRow && LOCK) {
				LOCK = false;

				if (resultsLen == 0) {
					//流表无数据的情况下
					for (var n = 0; n < sumCol; n++) {
						const resulti = items[index + n];
						if (n == 0) {
							resulti.startRow = true;
						}
						newItems.push(resulti);
						if (props.action === "edit" && n == sumCol - 1) {
							const addcell = { ...resulti }; //增加删除操作
							addcell.endRow = true;
							addcell.cellType = "operate";
							addcell.fieldShowText = "删除";
							addcell.mergedColCount = 1;
							addcell.mergedRowCount = 1;
							newItems.push(addcell);
						}
					}
				} else {
					//流表有数据的情况下

					for (let j = 0; j < resultsLen; j++) {
						for (let k = 0; k < sumCol; k++) {
							//i?
							if (results[j].ishj != "1") {
								//排除合计行

								const tmpItem = { ...items[index + k] };
								if (tmpItem.cellTableField && results[j]) {
									tmpItem.cellTableFieldValue = results[j][tmpItem.cellTableField];
								}

								if (k == 0) {
									tmpItem.startRow = true;
								}
								newItems.push(tmpItem);

								if (props.action === "edit" && k == sumCol - 1) {
									var addcell = { ...tmpItem }; //增加操作头部
									addcell.endRow = true;
									addcell.cellType = "operate";
									addcell.fieldShowText = "删除";
									addcell.mergedColCount = 1;
									addcell.mergedRowCount = 1;
									newItems.push(addcell);
								}
							}
						}
					}
				}

				// return false;
			} else if (item.cellRow > startRow) {
				//如果还有合计项继续拼接
				ISHJ = true;
				if (item.cellRow > saveRow) {
					if (props.action === "edit" && item.cellRow > startRow + 1) {
						//表示新的一行开始，此处增加结尾列、
						const addcell = { ...item }; //增加删除操作
						addcell.endRow = true;
						addcell.cellType = "show";
						addcell.fieldShowText = "";
						addcell.mergedColCount = 1;
						addcell.mergedRowCount = 1;
						newItems.push(addcell);
					}
					item.startRow = true;
				}
				if (item.cellTableField && results && resultsLen == 1) {
					item.cellTableFieldValue = results[0][item.cellTableField];
				}
				newItems.push(item);
			}
			saveRow = item.cellRow;
		});
		if (props.action === "edit" && ISHJ) {
			const addcell: any = {}; //增加删除操作
			addcell.endRow = true;
			addcell.cellType = "show";
			addcell.isShow = "1";
			addcell.fieldShowText = "";
			addcell.mergedColCount = 1;
			addcell.mergedRowCount = 1;
			newItems.push(addcell);
		}
	}
	return newItems;
}
function coverArrayToTable(data) {
	return data
		.filter(item => item.isShow === "1" && !isEmpty(item.cellType))
		.map((item, index) => {
			const rule: any = { props: {} };
			let isSumColumn = false; // 是否是合计列
			if (!isEmpty(item.cellTableFieldValue)) {
				rule.value = item.cellTableFieldValue || item.cellDefaultValue || "";
			}
			rule.startRow = item.startRow;
			rule.prop = item.cellTableField;
			rule.colObj = { ...item };
			rule.required = item.isRequired === "1";
			rule.colSpan = item.mergedColCount;
			rule.rowSpan = item.mergedRowCount;

			//配置脚本的有1、下拉级联脚本2、下拉禁用3、合计计算
			// if (!isEmpty(item.controlScript) && item.controlScript != "undefine") {
			//   let controlScript = decodeURIComponent(globalThis.atob(item.controlScript));
			//   try {
			//     if (controlScript.includes("excuteFormula")) {
			//       isSumColumn = true;
			//     }
			//     controlScript = JSON.parse(controlScript);
			//     rule.emit = controlScript;
			//   } catch (e) {
			//     proxy?.$showToast(`字段【${rule.prop}】计算规则格式错误，请检查！`);
			//     console.log(e);
			//   }
			// }
			// rule.props.readonly = props.formIsReadonly;
			rule.props.disabled = isSumColumn;
			switch (item.cellType) {
				case "show":
					rule.type = "text";
					rule.tipContent = item.inputTip;
					rule.value = item.fieldShowText;
					console.log('val',item.fieldShowText)
					break;
				case "input":
					let validateRules: any = [];
					if (rule.required && item.cellType !== "show") {
						validateRules.push({
							validator: (_rule, val, cb) => {
								if (isEmpty(val)) {
									cb(new Error());
                  console.log(rule);
                  proxy?.$showToast(`${rule.colObj.inputTip}`);
								} else {
									cb();
								}
							},
							trigger: ["blur", "change"]
						});
					}

					if (item.cellType !== "show" && !isEmpty(item.cellCheckRule)) {
          let checkRule: any = safeDecode(item.cellCheckRule);
          if (typeof checkRule === "string") {
            try {
              checkRule = eval("(" + checkRule + ")"); //页面传参

              rule.checkRule = checkRule;
              validateRules.push({
                validator: (rule, val, cb) => {
                  if (val) {
                    const isPassReg = new RegExp(checkRule.reg).test(val);
                    if (!isPassReg) {
                      cb(new Error());
                    } else {
                      cb();
                    }
                  } else {
                    cb();
                  }
                },
                type: "reg",
                message: "",
                trigger: ["blur", "change"]
              });
            } catch (e) {
              proxy?.$showToast(`字段【${rule.prop}】校验规则格式错误，请检查！`);
            }
          }
        }

					rule.validate = validateRules;
					switch (item.inputType) {
						case "text":
							rule.type = "input";
							break;
						case "number":
						case "percent":
							rule.type = "number-input";
							rule.props.maxDecimal = 4;
							break;
						case "int":
							rule.type = "number-input";
							rule.props.maxDecimal = 0;
							break;
						case "select":
						case "radio":
							rule.type = "select";
							rule.props.params = {};
							if (!isEmpty(item.cellDictId) && item.cellDictId != "undefine") {
								rule.props.params.options = [
									{
										label: "是",
										value: 1
									},
									{
										label: "否",
										value: 0
									}
								];
							}
							break;
						case "checkbox":
							rule.type = "select";
							rule.props.multiple = true;
							rule.props.params = {};
							if (!isEmpty(item.cellDictId) && item.cellDictId != "undefine") {
								rule.props.params.options = [
									{
										label: "是",
										value: 1
									},
									{
										label: "否",
										value: 0
									}
								];
							}
							break;
						case "textarea":
							rule.type = "input";
							rule.props.type = "textarea";
							rule.props.maxlength = 2000;
							rule.props.autosize = { minRows: 1, maxRows: 2 };
							break;
						case "date":
							rule.type = "date";
							rule.props.valueFormat = "x";
							break;
						case "file":
							rule.type = "file";
							rule.value = !isEmpty(rule.value) ? JSON.parse(rule.value) : "";
							break;
					}
					break;
				case "operate":
					rule.type = "link";
					break;
			}
			return rule;
		});
}

function safeDecode(encodedStr: string): string {
    if (!encodedStr) return "";
    try {
      const uriDecoded = decodeURIComponent(encodedStr);
      if (isValidBase64(uriDecoded)) {
        return globalThis.atob(uriDecoded);
      }
      return encodedStr;
    } catch (e) {
      console.error("解码失败:", e);
      return encodedStr;
    }
  }

	function isValidBase64(str: string): boolean {
    try {
      return globalThis.btoa(globalThis.atob(str)) === str;
    } catch (e) {
      return false;
    }
  }
// 添加全局错误监听
</script>
<style lang="scss" scoped>
.dynamic-table {
}
</style>
